package com.matrix.draft.sockettest.newprotocoltcp.util;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MyUtil {

    // 字符串转字节数组
    public static byte[] str2Bytes(String o, Charset charset) {
        return o.getBytes(charset);
    }

    // 重载
    public static byte[] str2Bytes(String o) {
        return o.getBytes(StandardCharsets.UTF_8);
    }

    // jdk序列化方式, 对象转字节数组
    public static byte[] Obj2Bytes(Object o) {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            oos.writeObject(o);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // jdk序列化方式, 字节数组转对象
    public static <T> T bytes2Obj(byte[] bytes, Class<T> cls) {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
        ) {
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 重载
    public static Object bytes2Obj(byte[] bytes) {
        return bytes2Obj(bytes, Object.class);
    }

}
